package com.systop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.systop.domain.to.GoodsTo;
import com.systop.domain.vo.GoodsStockVo;
import com.systop.entity.Goods;
import com.systop.entity.GoodsStock;
import com.systop.service.GoodsService;
import com.systop.service.GoodsStockService;
import com.systop.utils.sql.PageUtils;
import com.systop.utils.R;
import com.systop.validator.group.DelGroup;
import com.systop.validator.group.UpdateGroup;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: jsj
 * @Date: 2023/2/19
 */
@RestController
public class GoodsStockController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsStockService goodsStockService;

    @Autowired
    ThreadPoolExecutor executor;

    //根据商品id查询该商品的库存量
    @RequestMapping(value = "/queryStockByGoodsId",method = RequestMethod.GET)
    public R queryStockByGoodsId(@RequestParam Long goodsId){
        if (goodsId == 0){
            return R.error();
        }
        GoodsStock goodsStock = goodsStockService.getOne(new QueryWrapper<GoodsStock>().eq("goods_id", goodsId));

        if (goodsStock == null)
            return R.error("数据错误");
        return R.ok().put("goodsStock",goodsStock);
    }

    @RequestMapping(value = "/selectStockList",method = RequestMethod.GET)
    public R selectStockList(@RequestParam Map<String, Object> params){
        PageUtils page =
                goodsStockService.selectStockList(params);
        return R.ok().put("page", page);
    }

    @RequestMapping(value = "/queryStockList")
    public R queryStockList(@RequestBody Map<String, Object> params){
        System.out.println(params);
        //返回下来框中商品相关名称
        List<Goods> goodsList = goodsService.list(new QueryWrapper<Goods>().select("goods_id", "goods_name"));
        //返回页面查询数据
        PageUtils page =
                goodsStockService.queryStockList(params);
        return R.ok().put("page", page).put("goodsList",goodsList);
    }

    //分页查询库存信息
    @RequestMapping(value = "/addGoodsStock",method = RequestMethod.POST)
    public R addGoodsStock(@RequestBody List<GoodsStockVo> goodsStockVoList){
        //判断是否为空数据
        if (goodsStockVoList==null|| goodsStockVoList.size()==0 ) {
            return R.error("空数据错误");
        }

        //查询添加商品是否存在(只要有一个不存在就返回error信息)
        boolean isExist = goodsService.goodsIsExist(goodsStockVoList);
        if (!isExist) {
            return R.error("相关商品不存在，请检查数据是否正确");
        }

        //判断库存数是否存在异常
        if (goodsStockService.stockMatch(goodsStockVoList)) {
            return R.error("库存数存在异常，请检查后再提交信息");
        }

        /**
         *
         * 判断库存表中是否已经存在商品id
         *
         */
        //获取所有id
        List<Long> goodsIds = goodsStockVoList.stream().map(GoodsStockVo::getGoodsId).collect(Collectors.toList());

        //筛选出已经在库存中存在的商品的id
        List<Long> existGoodsIds = goodsStockService.existGoodsIds(goodsIds);

        //从所有添加的数据中筛选出未添加过的库存数据
        List<GoodsStockVo> nonExistentGoodsList = goodsStockVoList.stream().filter(
                goodsStockVo -> !existGoodsIds.contains(goodsStockVo.getGoodsId())
        ).collect(Collectors.toList());

        //从所有添加的数据中筛选出已添加过的库存数据
        List<GoodsStockVo> existentGoodsList = goodsStockVoList.stream().filter(
                goodsStockVo -> existGoodsIds.contains(goodsStockVo.getGoodsId())
        ).collect(Collectors.toList());

        /**
         * 如果匹配无异常开辟新线程执行库存添加
         */
        //库存表中不存在商品
        CompletableFuture.runAsync(() -> {
            List<GoodsStock> goodsStockList = nonExistentGoodsList.stream().map(
                    goodsStockVo -> {
                        //中间量
                        GoodsStock copyGoods = new GoodsStock();
                        BeanUtils.copyProperties(goodsStockVo, copyGoods);
                        //打印单个添加库存信息
                        // System.out.println(copyGoods);
                        return copyGoods;
                    }
            ).collect(Collectors.toList());

            //执行批量添加方法
            goodsStockService.saveBatch(goodsStockList);
        }, executor);

        //库存表中存在商品
        CompletableFuture.runAsync(()->{
            List<GoodsStock> goodsStockList = existentGoodsList.stream().map(
                    goodsStockVo -> {
                        //中间量
                        GoodsStock copyGoods = new GoodsStock();
                        BeanUtils.copyProperties(goodsStockVo, copyGoods);
                        //打印单个添加库存信息
                        // System.out.println(copyGoods);
                        return copyGoods;
                    }
            ).collect(Collectors.toList());

            //执行批量修改方法
            goodsStockService.updateBatchByGoodsId(goodsStockList);
        },executor);

        return R.ok();
    }

    @RequestMapping(value = "/updateStock",method = RequestMethod.POST)
    public R updateStock(@Validated(value = UpdateGroup.class) @RequestBody GoodsStockVo goodsStockVo){
        //判断是否为空数据
        if (goodsStockVo==null) {
            return R.error("空数据错误");
        }

        if (!goodsStockService.updateStock(goodsStockVo))
            return R.error("库存数据存在异常");

        return R.ok();
    }

    @RequestMapping(value = "/reduceStock",method = RequestMethod.DELETE)
    public R reduceStock(@Validated(value = DelGroup.class) @RequestBody GoodsStockVo goodsStockVo){
        //判断是否为空数据
        if (goodsStockVo==null) {
            return R.error("空数据错误");
        }

        if (!goodsStockService.updateStock(goodsStockVo))
            return R.error("库存数据存在异常");

        return R.ok();
    }
}
